"use strict";

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.default = void 0;
/**
 * 后续遍历节点并过滤，从根节点起始返回匹配节点
 * 如果子节点匹配，就认为父节点也匹配，因此不是每个节点均会调用 callback
 * @param treeNodes
 * @param callback
 * @param options
 * @returns
 */
const filter = (treeNodes, callback, options) => {
  const {
    level = 0,
    childrenKey = 'children',
    parent
  } = options || {};
  const filteredTreeNodes = [];
  const internalFilter = (nodes, result, options) => {
    const {
      level = 0,
      parent
    } = options || {};
    nodes.forEach((node, index) => {
      // 遍历子节点
      const children = node[childrenKey];
      if (children?.length) {
        const filteredChildren = [];
        internalFilter(children, filteredChildren, {
          level: level + 1,
          parent: node
        });
        if (!filteredChildren.length) {
          if (callback(node, {
            level,
            isMaybeLeaf: false,
            index,
            parent
          })) {
            result.push({
              ...node,
              [childrenKey]: node[childrenKey] === null ? null : undefined
            });
          }
          return;
        }
        return result.push({
          ...node,
          [childrenKey]: filteredChildren
        });
      }
      if (callback(node, {
        level,
        isMaybeLeaf: true,
        index,
        parent
      })) {
        return result.push({
          ...node,
          [childrenKey]: node[childrenKey] === null ? null : undefined
        });
      }
    });
  };
  internalFilter(treeNodes, filteredTreeNodes, {
    level,
    parent
  });
  return filteredTreeNodes;
};
var _default = exports.default = filter;